//
//  RHMePlantInfoFullChartVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/12.
//

#import "RHMePlantInfoFullChartVC.h"
#import "DevParamsAlertController.h"
#import "DeviceChartFieldModel.h"
#import "RHWindowTipManage.h"
#import "DevChartModel.h"
#import "AppDelegate.h"
#import "WSDatePickerView.h"
#import "RHMePlantInfoLineChartView.h"
#import "DevChartTypeModel.h"
#import "RHMePlantInfoBarChartView.h"

@interface RHMePlantInfoFullChartVC ()
@property (nonatomic ,strong) RHMePlantInfoLineChartView *lineChartView;

@property (nonatomic ,strong) RHMePlantInfoBarChartView *barChartView;

@property (nonatomic ,strong) DevChartModel *chartModel;

@property (nonatomic ,assign) RHPlantModel *plantModel;

@property (nonatomic ,assign) NSInteger toolType;

@property (nonatomic ,assign) BOOL isBarChart;

@property (nonatomic ,copy) NSString *url;//个别曲线请求的接口有的不一样
@end

@implementation RHMePlantInfoFullChartVC

- (instancetype)initWithModel:(DevChartModel *)chartModel plantModel:(RHPlantModel*)plantModel toolType:(NSInteger)toolType isBarChart:(BOOL)isBarChart requestUrl:(NSString*)url
{
    self = [super init];
    if (self) {
        self.chartModel = chartModel;
        self.plantModel = plantModel;
        self.toolType   = toolType;
        self.isBarChart = isBarChart;
        self.url = url;
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"Full Chart";
    self.isUnPopGes = YES;
    [self setupUI];
   
}



- (void)setupUI{
    if (self.isBarChart) {
        _barChartView = [[RHMePlantInfoBarChartView alloc] initWithFrame:CGRectMake(kSafe_top, 0,kUI_WINDOW_H - kSafe_top,kUI_WINDOW_W - kSafe_bottom) type:self.toolType isLandscape:YES];
        [self.bgView addSubview:_barChartView];
        kWeakSelf;
        _barChartView.fullChartBlock = ^{
            AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
               delegate.allowRotate = 0;
            if(@available(iOS 16.0, *)) {
                [weakSelf.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
                NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
                UIWindowScene *ws = (UIWindowScene *)array[0];
                UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
                geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
                [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
                     //业务代码
                }];
            }else{
                NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
                [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
            weakSelf.chartModel.isAllowScale = NO;
            
        };
        
        _barChartView.selectTopToolBlock = ^(NSInteger index) {
            [weakSelf selectTopTool:index];
        };
        
        _barChartView.subTimeBlock = ^{
            [weakSelf subTimeAction];
        };
        
        _barChartView.addTimeBlock = ^{
            [weakSelf addTimeAction];
        };

        _barChartView.changeTimeBlock = ^{
            [weakSelf changeDate];
        };
        
        [_barChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
        }];

     
        [self.barChartView setChartModel:self.chartModel];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf getDataFromNetwork:weakSelf.chartModel];
            
        });
    }else{
        _lineChartView = [[RHMePlantInfoLineChartView alloc] initWithFrame:CGRectMake(kSafe_top, 0,kUI_WINDOW_H - kSafe_top,kUI_WINDOW_W - kSafe_bottom) type:self.toolType isLandscape:YES];
        [self.bgView addSubview:_lineChartView];
        kWeakSelf;
        _lineChartView.fullChartBlock = ^{
            AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
               delegate.allowRotate = 0;
            if(@available(iOS 16.0, *)) {
                [weakSelf.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
                NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
                UIWindowScene *ws = (UIWindowScene *)array[0];
                UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
                geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
                [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
                     //业务代码
                }];
            }else{
                NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
                [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
            weakSelf.chartModel.isAllowScale = NO;
            
        };
        
        _lineChartView.selectTopToolBlock = ^(NSInteger index) {
            [weakSelf selectTopTool:index];
        };
        
        _lineChartView.subTimeBlock = ^{
            [weakSelf subTimeAction];
        };
        
        _lineChartView.addTimeBlock = ^{
            [weakSelf addTimeAction];
        };

        _lineChartView.changeTimeBlock = ^{
            [weakSelf changeDate];
        };
        
        [_lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
        }];

     
        [self.lineChartView setChartModel:self.chartModel];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf getDataFromNetwork:weakSelf.chartModel];
            
        });
    }
    
}

#pragma mark Action - Method
- (void)addTimeAction{
    if (self.chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (self.chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (self.chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (self.chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    [self getDataFromNetwork:self.chartModel];
}

- (void)subTimeAction{
    if (self.chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (self.chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (self.chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (self.chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];

    [self getDataFromNetwork:self.chartModel];
}

- (void)selectTopTool:(NSInteger)index {
    if (index == -1) {//Params
        DevParamsAlertController *vc = [[DevParamsAlertController alloc] initWithModel:self.chartModel isFull:YES];
        if(@available(iOS 16.0, *)) {
            [self presentViewController:vc animated:NO completion:nil];
        }else{
            [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
        }
        kWeakSelf;
        vc.resultBlock = ^{
            [weakSelf updateParams:weakSelf.chartModel];
        };
        return;
        
    }

    if (index == 0) {//Day
        self.chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.params = self.chartModel.dayParams;
        [self getDataFromNetwork:self.chartModel];
        return;

    }
    
    if (index == 1) {//Month
        self.chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.allDataArray = @[];
        self.chartModel.params = self.chartModel.monthParams;
        [self.lineChartView setChartModel:self.chartModel];
        [self getDataFromNetwork:self.chartModel];
        return;
    }
    
    if (index == 2) {//Year
        self.chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.allDataArray = @[];
        self.chartModel.params = self.chartModel.yearParams;
        [self.lineChartView setChartModel:self.chartModel];
        [self getDataFromNetwork:self.chartModel];
        return;
    }
    
    if (index == 4) {//Total
        //self.chartModel.timeType = TimeType_Total;
        return;
    }
}
 
//变更日期
- (void)changeDate{
    DevChartModel *chartModel = self.chartModel;
    //NSString *dateFormatStr = @"yyyy-MM-dd HH:mm";
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYear;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
       
        [self getDataFromNetwork:chartModel];
       
    }];
    datePickerV.dateLabelColor = UIColor.blueColor;//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
 
- (void)updateParams:(DevChartModel *)chartModel{
    
    if (chartModel.timeType == TimeType_Day) {
        [self getDataFromNetwork:chartModel];
    }

}


#pragma mark - Network
- (void)getDataFromNetwork:(DevChartModel *)chartModel{
    
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"plantId":@(self.plantModel.plant_id),@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    
    //电站详情
    [BaseModel startWithCompletionAPIKey:self.url argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        chartModel.allDataArray = request.responseJSONObject[@"data"];
//        chartModel.allDataArray = [chartModel getTestData];//测试数据
        if (self.isBarChart) {
            [self.barChartView setChartModel:chartModel];
        }else{
            [self.lineChartView setChartModel:chartModel];
        }
       
       
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
        
    
    
}



@end
